﻿using System;
using System.Data;
using MySql.Data.MySqlClient;

namespace wx_api.Data
{
    public class MysqlRepo : IRepo
    {
        IDbConnection db { get; set; }
        internal string connection_string { get; }
        public MysqlRepo(string connectionString)
        {
            this.connection_string = connectionString;
            db = new MySqlConnection(connectionString);
        }

        internal bool ClosedState { get { return db.State == ConnectionState.Closed; } }
        public virtual IDbConnection Connection { get { return db; } }
        public void Open()
        {
            try
            {
                if (ClosedState) db.Open();
            }
            catch (Exception ex)
            {
                var status = DealException(ex);

                switch (status)
                {
                    case 502: Open();
                        break;
                    default:
                        break;
                }
            }
        }
        public void Close()
        {
            if (!ClosedState) db.Close();
        }

        public void Dispose()
        {
            try
            {
                Close();
            }
            catch
            {
                //不处理关闭过程出错
            }
        }

        internal int DealException(Exception ex)
        {
            if (ex is InvalidOperationException)
            {
                if (ex.Message == "The connection had been disposed.")
                {
                    db = new MySqlConnection(connection_string);
                    return 502;
                }

                if (db.State != 0)
                {
                    return 0;
                }
            }
            return 0;
        }
    }
}
